package com.leo;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebHistory;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

import java.util.function.Consumer;

/**
 * @ClassName WebHistoryDemo
 * @Description
 * @Author wangss
 * @date 2020.07.01 11:07
 * @Version 1.0
 */
public class WebHistoryDemo extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        AnchorPane an = new AnchorPane();

        WebView webView = new WebView();
        WebEngine engine = webView.getEngine();
        engine.load("https://www.baidu.com");

        WebHistory history = engine.getHistory();
        ObservableList<WebHistory.Entry> entries = history.getEntries();

        HBox hBox = new HBox(20);
        Button b1 = new Button("前进");
        Button b2 = new Button("后退");
        Button b3 = new Button("信息");
        hBox.getChildren().addAll(b1, b2, b3);

        an.getChildren().addAll(hBox, webView);
        AnchorPane.setTopAnchor(webView, 30d);

        Scene scene = new Scene(an);
        primaryStage.setScene(scene);
        primaryStage.setHeight(800d);
        primaryStage.setWidth(1000d);
        primaryStage.setAlwaysOnTop(true);
        primaryStage.show();

        webView.prefWidthProperty().bind(an.widthProperty());
        webView.prefHeightProperty().bind(an.heightProperty());

        // 解决关窗口bug
        primaryStage.setOnCloseRequest(event -> {
            engine.load("");
            Platform.exit();
        });

        b3.setOnAction(event -> {
            System.out.println("当前业务索引：" + history.getCurrentIndex());
            System.out.println("最大存储数量：" + history.getMaxSize());
            System.out.println("当前存储数量：" + entries.size());

            entries.forEach(new Consumer<WebHistory.Entry>() {
                @Override
                public void accept(WebHistory.Entry entry) {
                    System.out.println(entry.getTitle());
                }
            });
        });

        b1.setOnAction(event -> {
            history.go(1);
        });

        b2.setOnAction(event -> {
            history.go(-1);
        });
    }
}
